package com.lsp.microorder.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lsp.microcommon.entity.DropOrder;
import com.lsp.microcommon.exception.CommonException;
import com.lsp.microorder.pay.dao.DropOrderDao;
import com.lsp.microorder.pay.param.PayResultParam;
import com.lsp.microorder.pay.service.DropOrderService;
import com.lsp.microorder.pay.service.TradeOrderPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class DropOrderServiceImpl implements DropOrderService {

    @Resource
    private DropOrderDao dropOrderDao;

    @Resource
    private TradeOrderPayService tradeOrderPayService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public void rollDropTask() {
//        针对调单表的数据遍历，查询交易订单的状态
        List<DropOrder> dropOrders = dropOrderDao.selectList(null);
        for (DropOrder dropOrder : dropOrders) {
            threadPoolExecutor.execute(() -> {
                checkPayOrder(dropOrder);
            });
        }
    }


    private void checkPayOrder(DropOrder dropOrder) {
        try {
            log.info("查询订单状态");
//                查询订单状态,需要返回交易订单号
            String tradeNo = tradeOrderPayService.payStates(dropOrder.getOrderNo(), dropOrder.getPayType());
//                处理业务订单状态，调用payFinish方法
            PayResultParam param = new PayResultParam();
            param.setOrderNo(dropOrder.getOrderNo());
            param.setPayTradeNo(tradeNo);
//                payFinish该方法针对集群部署时用了分布式锁
            tradeOrderPayService.payFinish(param);
//                rechargeInfoService.updatePayFlag(dropOrder.getOrderNo());
//                根据orderNo删除掉单数据
            log.info("订单状态为success时删除订单");
            dropOrderDao.deleteById(dropOrder.getId());
        } catch (Exception e) {
//                否则轮询次数+1
            if (dropOrder.getNum() >= 10) {
                log.info("关闭订单，并删除掉单数据");
                tradeOrderPayService.closePay(dropOrder.getOrderNo(), dropOrder.getPayType());
                dropOrderDao.deleteById(dropOrder.getId());
                throw new CommonException("订单关闭");
            }
            log.info("轮询次数+1");
            dropOrderDao.update(null, new LambdaUpdateWrapper<DropOrder>()
                    .set(DropOrder::getNum, dropOrder.getNum() + 1)
                    .eq(DropOrder::getId, dropOrder.getId()));
        }
    }
}
